﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using Tools.Cache;
using Tools.Model;
using Tools.Utils;

namespace Tools.Service
{
    /// <summary>
    /// 代码格式化
    /// </summary>
    public class CodeService
    {
        /// <summary>
        /// 格式化json字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string ConvertJsonString(string str)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 获取两个时间之间的间隔(item1-天数，item2-小时数，item3-分钟数，item4-秒数，item5-时间戳)
        /// </summary>
        /// <returns></returns>
        private (string, string, string, string, string) GetDateInterval(DateTime beginDateTime, DateTime endDateTime)
        {
            var a = endDateTime - beginDateTime;

            return (a.Days.ToString(), a.Hours.ToString(), a.Minutes.ToString(), a.Seconds.ToString(), a.ToString());
        }

        /// <summary>
        /// 获取城市邮编
        /// </summary>
        /// <param name="city"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public List<CityZipCodeModel> GetCityZipCodeList(string parentCity)
        {
            var cityZipCodeKey = "city_zip_code";
            var cache = new CacheHelper();
            var list = new List<CityZipCodeModel>();
            var obj = cache.Get(cityZipCodeKey);

            if (obj == null)
            {
                list = FileHelper.FileReadStr(cityZipCodeKey).DeserializeObjects<CityZipCodeModel>();
                cache.Set(cityZipCodeKey, list, new TimeSpan(1, 0, 0), true);
            }
            else
            {
                list = obj as List<CityZipCodeModel>;
            }

            if (!string.IsNullOrWhiteSpace(parentCity)) 
            {
                list = list.FindAll(t => t.ParentCity == parentCity);
            }
            
            return list;
        }
    }
}
